package com.bnz.test;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;


import java.nio.charset.StandardCharsets;

/**
 * rabbitmq Hello World 模型示例
 * 消息消费者
 */
public class MessageConsumer {

    /**
     * 消息队列名称
     */
    public static final String QUEUE_NAME = "SF_To_Idea_DynamicFlightData_Queue_dev2";

    public static void main(String[] args) throws Exception {
        // 连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置服务地址
        factory.setUri("amqp://data-ep03-dev.silassz.com");
        // 设置Virtual Hosts
        factory.setVirtualHost("test1");
        // 设置用户名
        factory.setUsername("idea_user");
        // 设置密码
        factory.setPassword("Idea@2023");
        // 获取连接、建立通道
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // 绑定消息队列
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        System.out.println(" [Consumer(hello world)] Waiting for messages.");
        // 消息处理回调；当收到消息后会执行该消息处理逻辑
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [Consumer(hello world)] Received '" + message + "'");
        };
        // 订阅消息 (第二个参数为true表示收到消息自动确认)
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {
            System.out.println("consumerTag = " + consumerTag);
        });
    }
}